﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ProductManager
{
    public partial class AddCategory : Form
    {
        List<string[]> _categoryTree = new List<string[]>();

        public AddCategory()
        {
            InitializeComponent();
            _categoryTree.Add(new string[] { "/", "/" });
        }

        private DataTable GetChildCategory(string parentID)
        {
            if (parentID == "/")
            {
                return DBAccess.GetRootCategory();
            }
            else
            {
                return DBAccess.GetChildCategory(parentID);
            }
        }

        private void RefreshCategory()
        {
            DataTable child;
            string indent = "";

            lvCategory.Items.Clear();
            foreach (string[] category in _categoryTree)
            {
                lvCategory.Items.Add(new ListViewItem(category));
            }
            for (int i = 0; i < _categoryTree.Count - 1; i++)
            {
                indent += "-|-";
            }
            child = GetChildCategory(_categoryTree[_categoryTree.Count - 1][1]);
            foreach (DataRow row in child.Rows)
            {
                lvCategory.Items.Add(new ListViewItem(new string[] {
                    indent + row["Name"].ToString(), row["ID"].ToString() }));
            }
        }

        private void lvCategory_DoubleClick(object sender, EventArgs e)
        {
            if (lvCategory.SelectedIndices.Count == 1)
            {
                if (lvCategory.SelectedIndices[0] < _categoryTree.Count)
                {
                    while (_categoryTree.Count - 1 > lvCategory.SelectedIndices[0])
                    {
                        _categoryTree.RemoveAt(_categoryTree.Count - 1);
                    }
                }
                else
                {
                    _categoryTree.Add(new string[] {
                        lvCategory.SelectedItems[0].SubItems[0].Text,
                        lvCategory.SelectedItems[0].SubItems[1].Text });
                }
                RefreshCategory();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (lvCategory.SelectedIndices.Count == 1)
            {
                string id = lvCategory.SelectedItems[0].SubItems[1].Text;
                if (id != "/")
                {
                    ((CategoryManager)Owner).AddExistCategory(id);
                }
            }
        }

        private void AddCategory_Load(object sender, EventArgs e)
        {
            RefreshCategory();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            Close();
        }
    }
}
